<template>
    <div class="chat-window">
      <div class="chat-header">
        <span>与 {{ targetUser }} 聊天</span>
        <button class="close-btn" @click="closeChat">×</button>
      </div>
      <div class="chat-body">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="{ 'sent': message.sender === 'me', 'received': message.sender === 'other' }">
          <div class="message-content">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      <div class="chat-input">
        <input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  
  const props = defineProps({
    targetUser: String, // 聊天对象的用户名
  });
  
  const emit = defineEmits(['close']);
  
  const messages = ref([]); // 存储聊天消息
  const newMessage = ref(''); // 输入框中的新消息
  let socket = null; // WebSocket 实例
  
  // 初始化 WebSocket 连接
  const initWebSocket = () => {
    const userId = localStorage.getItem('userId'); // 从本地存储获取当前用户ID
    if (!userId) {
      alert('请先登录！');
      return;
    }
  
    // 创建 WebSocket 连接
    socket = new WebSocket(`ws://localhost:8080/ws?userId=${userId}`);
  
    // 监听消息接收
    socket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      messages.value.push({ sender: 'other', content: message.content, time: new Date().toLocaleTimeString() });
    };
  
    // 监听连接关闭
    socket.onclose = () => {
      console.log('WebSocket 连接已关闭');
    };
  
    // 监听连接错误
    socket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };
  };
  
  // 发送消息
  const sendMessage = () => {
    if (newMessage.value.trim()) {
      const message = {
        sender: 'me',
        content: newMessage.value,
        time: new Date().toLocaleTimeString(),
        targetUserId: props.targetUser, // 发送给目标用户
      };
  
      // 通过 WebSocket 发送消息
      if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify(message));
        messages.value.push(message); // 将消息添加到本地消息列表
        newMessage.value = ''; // 清空输入框
      } else {
        console.error('WebSocket 连接未就绪');
      }
    }
  };
  
  // 关闭聊天窗口
  const closeChat = () => {
    if (socket) {
      socket.close(); // 关闭 WebSocket 连接
    }
    emit('close'); // 通知父组件关闭聊天窗口
  };
  
  // 组件挂载时初始化 WebSocket
  onMounted(() => {
    initWebSocket();
  });
  
  // 组件卸载时关闭 WebSocket
  onUnmounted(() => {
    if (socket) {
      socket.close();
    }
  });
  </script>
  
  <style scoped>
  .chat-window {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 300px;
    height: 400px;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
  }
  
  .chat-header {
    padding: 10px;
    background: #4684e2;
    color: #fff;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .close-btn {
    background: none;
    border: none;
    color: #fff;
    font-size: 20px;
    cursor: pointer;
  }
  
  .chat-body {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background: #f9f9f9;
  }
  
  .message {
    margin-bottom: 10px;
  }
  
  .message-content {
    padding: 8px;
    border-radius: 4px;
    max-width: 80%;
  }
  
  .message-time {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
  }
  
  .sent .message-content {
    background: #4684e2;
    color: #fff;
    margin-left: auto;
  }
  
  .received .message-content {
    background: #e1e1e1;
    color: #000;
    margin-right: auto;
  }
  
  .chat-input {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
    background: #fff;
  }
  
  .chat-input input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-right: 10px;
  }
  
  .chat-input button {
    padding: 8px 12px;
    background: #4684e2;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  </style>